package com.cl.activity;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cl.db.dao.BlackNumberDao;
import com.cl.domain.BlackNumberInfo;
import com.cl.safe.R;

public class CallSmsSafeActivity extends Activity {
	private ListView lv_callsms_safe;
	private MyListAdapte adapter;
	private List<BlackNumberInfo> infos;
	private BlackNumberDao dao;
	private LinearLayout ll_loading;
	private int offset = 0;
	private int maxnumber = 20;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_call_sms_safe);
		lv_callsms_safe = (ListView) findViewById(R.id.lv_callsms_safe);
		dao = new BlackNumberDao(getApplicationContext());
		ll_loading = (LinearLayout) findViewById(R.id.ll_loading);
		fillData();
		// listview注册一个滚动事件的监听器。
		lv_callsms_safe.setOnScrollListener(new OnScrollListener() {
			// 当滚动的状态发生变化的时候。
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// 判断当前listview滚动的位置
				switch (scrollState) {
				case OnScrollListener.SCROLL_STATE_IDLE:// 空闲状态
					// 获取最后一个可见条目在集合里面的位置。
					int lastVisiblePosition = view.getLastVisiblePosition();
					// 如果停在最后位置，继续加载数据
					if(lastVisiblePosition == infos.size() - 1) {
						System.out.println("列表被移动到了最后一个位置，加载更多的数据。。。");
						offset += maxnumber;
						fillData();
					}
					break;
				case OnScrollListener.SCROLL_STATE_FLING:// 惯性滑行状态
					break;
				case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:// 手指触摸滚动
					break;
				default:
					break;
				}
			}
			// 滚动的时候调用的方法。
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				
			}
		});
	}
	private void fillData() {
		//加载数据，进度条可见
		ll_loading.setVisibility(View.VISIBLE);
		new Thread(){
			public void run() {
				if(infos == null) {
					infos = dao.findPart(offset, maxnumber);
				}else {// 原来已经加载过数据了。
					infos.addAll(dao.findPart(offset, maxnumber));
				}
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						//数据加载完毕，进度条不可见
						ll_loading.setVisibility(View.INVISIBLE);
						if(adapter == null) {
							adapter = new MyListAdapte();
							lv_callsms_safe.setAdapter(adapter);
						}else {
							adapter.notifyDataSetChanged();
						}
					}
				});
			};
		}.start();
	}
	
	
	private View v;
	private class MyListAdapte extends BaseAdapter {
		private static final String TAG = "MyListAdapte";
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return infos.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			String number = infos.get(position).getNumber();
			ViewHolder holder = new ViewHolder();
			String mode = infos.get(position).getMode();
			//1.减少内存中view对象创建的个数
			if(convertView == null) {
				v = View.inflate(CallSmsSafeActivity.this, R.layout.list_item_callsms, null);
				holder.tv_number = (TextView) v.findViewById(R.id.tv_black_number);
				holder.tv_mode = (TextView) v.findViewById(R.id.tv_block_mode);
				holder.iv_delete = (ImageView) v.findViewById(R.id.iv_delete);
				Log.i(TAG, "position: "+position+" v: "+v);
				//当孩子生出来的时候找到他们的引用，存放在记事本，放在父亲的口袋
				v.setTag(holder);
			}else {
				v = convertView;
				Log.i(TAG,"厨房有历史的view对象，复用历史缓存的view对象："+position);
				holder = (ViewHolder) v.getTag();
			}
			
			holder.tv_number.setText(number);
			if("1".equals(mode)){
				holder.tv_mode.setText("电话拦截");
			}else if("2".equals(mode)){
				holder.tv_mode.setText("短信拦截");
			}else{
				holder.tv_mode.setText("全部拦截");
			}
			holder.iv_delete.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					AlertDialog.Builder builder = new Builder(CallSmsSafeActivity.this);
					builder.setTitle("警告");
					builder.setMessage("是否要删除该黑名单");
					builder.setNegativeButton("取消", null);
					builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							//删除数据库的内容
							dao.delete(infos.get(position).getNumber());
							//更新界面。
							infos.remove(position);
							//通知listview数据适配器更新
							adapter.notifyDataSetChanged();
							dialog.dismiss();
						}
					});
					builder.show();
				}
			});
			return v;
		}
	}
	/**
	 * view对象的容器
	 *记录孩子的内存地址。
	 *相当于一个记事本
	 */
	static class ViewHolder {
		TextView tv_number;
		TextView tv_mode;
		ImageView iv_delete;
	}
	
	private EditText et_blacknumber;
	private CheckBox cb_phone;
	private CheckBox cb_sms;
	//添加黑名单
	public void addBlackNumber(View v) {
		View view = View.inflate(this, R.layout.dialog_add_blacknumber, null);
		AlertDialog.Builder builder = new Builder(this);
		final AlertDialog dialog = builder.create();
		dialog.setView(view, 0, 0, 0, 0);
		dialog.show();
		et_blacknumber = (EditText) view.findViewById(R.id.et_blacknumber);
		cb_phone = (CheckBox) view.findViewById(R.id.cb_phone);
		cb_sms = (CheckBox) view.findViewById(R.id.cb_sms);
		Button ok = (Button) view.findViewById(R.id.ok);
		Button cancel = (Button) view.findViewById(R.id.cancel);
		ok.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String number = et_blacknumber.getText().toString().trim();
				String mode = null;
				if(TextUtils.isEmpty(number)) {
					Toast.makeText(CallSmsSafeActivity.this, "黑名单号码不能为空", 0).show();
					return;
				}
				if(cb_phone.isChecked()&&cb_sms.isChecked()){
					//全部拦截
					mode = "3";
				}else if(cb_phone.isChecked()) {
					//电话拦截
					mode = "1";
				}else if(cb_sms.isChecked()) {
					//短信拦截
					mode = "2";
				}else {
					Toast.makeText(CallSmsSafeActivity.this, "请勾选拦截模式", 0).show();
				}
				dao.add(number, mode);
				BlackNumberInfo info = new BlackNumberInfo();
				info.setMode(mode);
				info.setNumber(number);
				infos.add(0, info);
				adapter.notifyDataSetChanged();
				dialog.dismiss();
			}
		});
		cancel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		
	}
}
